package musicbox;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;

import musicbox.Metro.RepeatingDelayedMessage;
import neuralmusic.brain.module.BasicDelayed;
import neuralmusic.brain.module.BrainException;
import neuralmusic.brain.module.Scheduler;
import static java.lang.System.*;

public class Metro {
	
	
	private Receiver recv;
	private ShortMessage mess;
	public boolean running;
	private double period;
	private RepeatingDelayedMessage beat;
	private Scheduler sched;

	Metro(Receiver recv,int chan,Scheduler sched,double tempoInBPM){
		this.recv=recv;
		mess = new ShortMessage();
		period=60.0/tempoInBPM;
		// beat = new RepeatingDelayedMessage(sched);
		try {
			mess.setMessage(ShortMessage.NOTE_ON, chan, 60, 100);
		} catch (InvalidMidiDataException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		running=false;
		this.sched=sched;
	}
	
	
	void start(){
		if (running) return;
		out.println(" MEtro ON");
		if (beat != null) beat.fireAtDelta(1.0);
		running=true;
	}
	
	void adjust(double tAt,double tempo){
		if (beat != null) beat.running=false;
		beat = new RepeatingDelayedMessage(sched);
		beat.fireAt(tAt);
		period=tempo;
	}

	public class RepeatingDelayedMessage extends BasicDelayed {

		
		boolean running=true;
		
		RepeatingDelayedMessage(Scheduler s){super(s);}
		
		@Override
		public void fireImpl(Scheduler sched) throws BrainException {
			if (! running ) return;
			out.println("BEAT");
			recv.send(mess,-1);
			fireAtDelta(period);
		} 

	}

}
